package hsb.ruoyi.framework.aspectj;


import hsb.ruoyi.common.annotation.DataScope;
import hsb.ruoyi.common.core.domain.BaseEntity;
import hsb.ruoyi.common.core.domain.entity.SysRole;
import hsb.ruoyi.common.core.domain.entity.SysUser;
import hsb.ruoyi.common.core.domain.model.LoginUser;
import hsb.ruoyi.common.utils.SecurityUtils;
import hsb.ruoyi.common.utils.StringUtils;
import io.quarkus.arc.Priority;
import io.quarkus.arc.runtime.InterceptorBindings;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */

@DataScope
@Interceptor
@Priority(2020)
public class DataScopeAspect {
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";


    @AroundInvoke
    public Object execute(InvocationContext context) throws Exception {

        clearDataScope(context);
        Set<Annotation> bindings = InterceptorBindings.getInterceptorBindings(context);

        DataScope controllerDataScope = null;
        // 遍历所有注解，过滤出SendMessage类型的
        for (Annotation binding : bindings) {
            if (binding instanceof DataScope) {
                controllerDataScope = (DataScope) binding;
                break;
            }
        }


        handleDataScope(context, controllerDataScope);


        return context.proceed();
    }


    protected void handleDataScope(InvocationContext context, DataScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
                dataScopeFilter(context, currentUser, controllerDataScope.deptAlias(),
                        controllerDataScope.userAlias());
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param context   上下文
     * @param user      用户
     * @param userAlias 别名
     */
    public static void dataScopeFilter(InvocationContext context, SysUser user, String deptAlias, String userAlias) {
        StringBuilder sqlString = new StringBuilder();

        for (SysRole role : user.getRoles()) {
            String dataScope = role.getDataScope();
            if (DATA_SCOPE_ALL.equals(dataScope)) {
                sqlString = new StringBuilder();
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
                        role.getRoleId()));
            } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
            } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
                        deptAlias, user.getDeptId(), user.getDeptId()));
            } else if (DATA_SCOPE_SELF.equals(dataScope)) {
                if (StringUtils.isNotBlank(userAlias)) {
                    sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
                }
            }
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = context.getParameters()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity baseEntity) {
                baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final InvocationContext context) {
        Object[] parameters = context.getParameters();
        if (parameters == null || parameters.length == 0) {
            return;
        } else {
            Object params = parameters[0];
            if (params instanceof BaseEntity) {
                ((BaseEntity) params).getParams().put(DATA_SCOPE, "");
            }
        }
    }
}
